/**
 * Created by Dave on 2017/3/13.
 */

var tpl=require('../../node_modules/baidutemplate/baiduTemplate.js');
var jsonUtil = require('../util/jsonUtil');
var appConfigEnv = require('../../db/appConfigEnvDB');
var envdb = new appConfigEnv();
var appConfigFile = require('../../db/appConfigFileDB');
var filedb = new appConfigFile();
var appConfigHistory = require('../../db/appConfigHistoryDB');
var historydb = new appConfigHistory();
var appConfigSet = require('../../db/appConfigSetDB');
var setdb = new appConfigSet();
var logger = require('../log4js/log4js').logger('appConfigEnv');
var transChar = "&#1234";
function MaxVersionComparator(e1,e2){
    return new Number(e1.version)-new Number(e2.version);
}
function insert(db,data){
    logger.debug("Try to insert env");
    return new Promise(function(resolve,reject){
        db.insert(null, data, function (err, ret) {
            if (err != null){
                console.log(err);
                reject(err);
            }
            else {
                logger.debug("Inserted.");
                resolve(ret);
            }
        });
    });
}
function get(db,stmt){
    return new Promise(function(resolve,reject){
        db.getWithParam(null,stmt, function (err, ret) {
            if(ret==null||ret.length<=0)
                ret=[];
            jsonUtil(ret);
            resolve(ret);
        });
    });
}
function getMax(db,stmt,comparator){
    return new Promise(function(resolve,reject){
        get(db,stmt).then(function (ret) {
            var res=ret.getMax(comparator);
            resolve(res);
        })
    });
}
module.exports=configManager;
function ImplConfigFile(configFile,env){
    /*return configFile.value.replace(/<%=([^%>]+)?%>/g, function(s0, s1){
        return env.value[s1];
    });*/
    tpl.template.LEFT_DELIMITER ='{%';
    tpl.template.RIGHT_DELIMITER = '%}';
    tpl.template.ESCAPE = false;
    //转义 换行符
    configFile.value= configFile.value.replace(/\n/g,transChar);
    return tpl.template(configFile.value,env.value);
}
function configManager(){
    configManager.prototype.getDef=function (files,serviceName) {
        var response={
            configMaps:[],
            volumes:[],
            volumeMounts:[]
        };
        var id=0;
        for(var dir in files){
            var cm={
                "kind": "ConfigMap",
                "apiVersion": "v1",
                "data": {
                    //"file1":"content-of-the-file1"
                },
                "metadata": {
                    "name":"configmap-"+serviceName+"-"+id,
                    "labels":{
                        "app":serviceName
                    }
                }
            };
            for(var name in files[dir]){
                cm.data[name]=files[dir][name];
                response.volumeMounts.push(
                    {
                        "name":"configmap-"+serviceName+"-volume-"+id,
                        "mountPath":dir+"/"+name,
                        "subPath":name
                    }
                );
            }
            response.configMaps.push(cm);
            response.volumes.push(
                {
                    "name":"configmap-"+serviceName+"-volume-"+id,
                    "configMap":{
                        "name":"configmap-"+serviceName+"-"+id,
                    }
                }
            );
            /*response.volumeMounts.push(
                {
                    "name":"configmap-"+serviceName+"-volume-"+id,
                    "mountPath":dir
                }
            );*/
            id++;
        }
        return response;
    }
    configManager.prototype.implement=function (imageName, imageVersion, namespace, envName, envVersion) {
        var env=null;
        var configs=null;
        return getMax(setdb,{namespace:namespace,imageName:imageName,imageVersion:imageVersion},MaxVersionComparator).then(function (cfs) {
            if(cfs==null||cfs.files==null||cfs.files.length<=0)
                throw "no file";
            var files=cfs.files;
            env={value:cfs.envs[envName]};
            var querys=[];
            for(var index in files) {
                querys.push(getMax(
                    filedb,
                    {namespace: namespace, imageName: imageName, filepath: files[index].filepath, version: files[index].version},
                    MaxVersionComparator
                ));
            }
            return Promise.all(querys);
        }).then(function (val) {
            if(val==null)
                reject();
            configs=val;
            /*return getMax(
                envdb,
                {namespace:namespace,imageName:imageName,name:envName,version:envVersion},
                MaxVersionComparator
            );*/
            return new Promise(function (resolve) {
                resolve(env);
            })
        }).then(function (val) {
            if(val==null)
                reject();
            env=val;
            var impls=[];
            for(var index in configs) {
                impls.push(new Promise(function (resolve, reject) {
                    var data={};
                    var _orgin = ImplConfigFile(configs[index], env);

                    _orgin  =_orgin
                        .replace(/\&\#1234/g,'\n')
                        .replace(/\&\#92;/g,'\\')
                        .replace(/\&\#39;/g,"'");

                    data[configs[index].filepath]= _orgin;
                    resolve(data);
                }));
            }
            return Promise.all(impls);
        }).then(function (val) {
            return new Promise(function (resolve) {
                var files={};
                var getDir=function(path){
                    return path.substring(0,path.lastIndexOf("/"));
                }
                var getFilename=function (path) {
                    return path.substring(path.lastIndexOf("/")+1);
                }
                //处理为dir=>{filename=>content}
                for(var index in val) {
                    for(var path in val[index]) {
                        var dir = getDir(path);
                        var filename = getFilename(path);
                        if (!files.hasOwnProperty(dir))
                            files[dir] = {};
                        files[dir][filename]=val[index][path];
                    }
                }
                resolve(files);
            })
        }).catch(function (err) {
            console.log(err);
            return new Promise(function(resolve){
                resolve(null);
            });
        });
    }
}